package cn.rui.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.rui.common.Content;
import cn.rui.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义权限验证接口扩展
 *
 * @author 徽州大都督
 * @date 2021/05/13
 */
@Component    // 保证此类被SpringBoot扫描，完成sa-token的自定义权限验证扩展
public class StpInterfaceImpl implements StpInterface {


    @Autowired
    private PermissionService permissionService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginKey) {

        if (redisTemplate.hasKey (Content.PERMISSION_CODE + loginId.toString ())) {
            List permissionList = redisTemplate.opsForList ().range (Content.PERMISSION_CODE + loginId.toString (), 0, -1);
            return permissionList;
        }

        List<String> list = permissionService.findByUserUuid (loginId.toString ());
        redisTemplate.opsForList ().leftPushAll (Content.PERMISSION_CODE + loginId.toString (), list);
        return list;
    }


    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginKey) {

        // 本list仅做模拟，实际项目中要根据具体业务逻辑来查询角色
        List<String> list = new ArrayList<String> ();
        list.add ("admin");
        list.add ("super-admin");
        return list;
    }
}
